package cn.gson.springboot.model.service;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;

import cn.gson.springboot.model.dao.DestroyDao;
import cn.gson.springboot.model.dao.DestryDetailDao;
import cn.gson.springboot.model.dao.DoctoradviceDetailDAO;
import cn.gson.springboot.model.dao.DrugApplyDao;
import cn.gson.springboot.model.dao.DrugDao;
import cn.gson.springboot.model.dao.DrugapplyDetailDao;
import cn.gson.springboot.model.dao.DrugstorageCheckDao;
import cn.gson.springboot.model.dao.DrugstoragecheckDetailDao;
import cn.gson.springboot.model.dao.InhospitalstorageDao;
import cn.gson.springboot.model.dao.InventoryDao;
import cn.gson.springboot.model.dao.OutpatientstorageDao;
import cn.gson.springboot.model.dao.PublicDurgDao;
import cn.gson.springboot.model.dao.PublicdurgDetailDao;
import cn.gson.springboot.model.dao.ReturnGoodDao;
import cn.gson.springboot.model.dao.ReturnGoodsDetailDao;
import cn.gson.springboot.model.mapper.AdviceDetailsMappers;
import cn.gson.springboot.model.mapper.DrugRoomMappers;
import cn.gson.springboot.model.pojos.Destroy;
import cn.gson.springboot.model.pojos.DestryDetail;
import cn.gson.springboot.model.pojos.DoctoradviceDetail;
import cn.gson.springboot.model.pojos.Drug;
import cn.gson.springboot.model.pojos.DrugApply;
import cn.gson.springboot.model.pojos.DrugapplyDetail;
import cn.gson.springboot.model.pojos.DrugstorageCheck;
import cn.gson.springboot.model.pojos.DrugstoragecheckDetail;
import cn.gson.springboot.model.pojos.InhospitalStorage;
import cn.gson.springboot.model.pojos.Inventory;
import cn.gson.springboot.model.pojos.LookIllness;
import cn.gson.springboot.model.pojos.OutpatientStorage;
import cn.gson.springboot.model.pojos.PublicDurg;
import cn.gson.springboot.model.pojos.PublicdurgDetail;
import cn.gson.springboot.model.pojos.ReturnGood;
import cn.gson.springboot.model.pojos.ReturnGoodsDetail;
import cn.gson.springboot.model.vo.AdviceVo;
import cn.gson.springboot.model.vo.DestructionVo;
import cn.gson.springboot.model.vo.DrugfyVo;
import cn.gson.springboot.model.vo.DrugqlVo;
import cn.gson.springboot.model.vo.DrugscheckVo;
import cn.gson.springboot.model.vo.InHospitalStorageVo;
import cn.gson.springboot.model.vo.OutpatientStorageVo;
import cn.gson.springboot.model.vo.ReturndrugVo;
@Service
@Transactional(rollbackFor=Exception.class)
public class DrugRoomService {
	@Autowired
	private DrugRoomMappers drugmapper;
	
	//请领表
	@Autowired
	private DrugApplyDao drugapplydao;
	
	//请领详情
	@Autowired
	private DrugapplyDetailDao drugapplydetaildao;
	
	//获取药品
	@Autowired
	private DrugDao drugdao;
	
	//门诊库存
	@Autowired
	private OutpatientstorageDao outpatientDao;
	
	//门诊库存
	@Autowired
	private 	InhospitalstorageDao inhosdao;

	//药品的dao
    @Autowired
	private DrugDao drugsdao;
   
	@Autowired
	private PublicDurgDao fydao;
	
	@Autowired
	private PublicdurgDetailDao fyxxdao;
	
	@Autowired
	private DoctoradviceDetailDAO yzdao;
	
	@Autowired
	private AdviceDetailsMappers  advicedetailsmapper;	
	
	//退药表dao
	@Autowired
	private ReturnGoodDao gooddao; 
	
	//退药详情表dao
	@Autowired
	private ReturnGoodsDetailDao gooddeyaildao; 
	
	//库存表dao
	@Autowired
	private InventoryDao Inventorydao; 
	
	@Autowired
	private DestroyDao destroydao; //销毁表dao
	
	@Autowired
	private DestryDetailDao destrydetaildao; //销毁详情表dao
	
	@Autowired
	private DrugstorageCheckDao Drugcdao; //盘点表dao
	
	@Autowired
	private DrugstoragecheckDetailDao drugcdetaildao; //盘点详情表dao
	
	//药房入库查询药品基本信息
	public JSONArray selectDrugRoomInStorage(String drugname,Integer drug_number,String type_name) {
		return drugmapper.selectDrugRoomInStorage(drugname,drug_number,type_name);
	}
	
	//新请领记录
	public void addApply(DrugqlVo drugqlVo) {
		//获取药品信息进行新增
		DrugApply drugapply = drugqlVo.getDrugapply();
		
		DrugApply save = drugapplydao.save(drugapply);
		
		List<DrugapplyDetail> details = drugqlVo.getDrugapplyDetail();
		
		//循环
		for (DrugapplyDetail pur : details) {
		//添加药品信息
		pur.setDrugApply(drugapply);
		//查询药品
		Drug drug = drugdao.findById(pur.getDrug().getDrugNumber()).get();
		//重新赋值药品对象
		pur.setDrug(drug);
		drugapplydetaildao.save(pur);
		}
	}
	
	 //药房入库查询药品基本信息
	public JSONArray  selectDrugsInStorage(String drugapply_people) {
		return drugmapper.selectDrugsInStorage(drugapply_people);
	}
	
	 //药房入库查看详情
	public JSONArray selectDrugsInStorageDetails(Integer drugapply_id,Integer outbound_zt) {
		return drugmapper.selectDrugsInStorageDetails(drugapply_id,outbound_zt);
	}
	
	// 确认收货新增门诊库存
	public  void addoutpatientStorage(Integer drug_number,Integer outpatient_pici,
																	  Integer outpatient_storage_amount,
																	  Date outpatient_storage_startdate,
																	  Date outpatient_storage_usedate) {
		drugmapper.addoutpatientStorage(drug_number, outpatient_pici, outpatient_storage_amount, outpatient_storage_startdate, outpatient_storage_usedate);
	}
	   
     //确认收货新增住院库存
	public  void addinhospitalStorage(Integer drug_number,Integer inhospital__pici,
																	 Integer inhospital__storage_amount,
																	 Date inhospital_storage_startdate,
																	 Date inhospital_storage_usedate) {
		drugmapper.addinhospitalStorage(drug_number, inhospital__pici, inhospital__storage_amount, inhospital_storage_startdate, inhospital_storage_usedate);
	}

	//收货之后修改请领状态 
	public  void  updateDrugApply_state(Integer drugapply_state,Integer drugapply_type,Integer drugapply_id) {
		drugmapper.updateDrugApply_state(drugapply_state,drugapply_type, drugapply_id);
	}
	      
	  
	//收货之后修改出库状态
   public  void  updateOutBound_state(Integer outbound_state,Integer outbound_number) {
	   drugmapper.updateOutBound_state(outbound_state, outbound_number);
   }
   
   //门诊入库
   public void saveDrugRoomStorage(OutpatientStorageVo outvo,Integer drugApplyId,Integer outbound_number) {
	     //System.out.println("drugApplyId-----------"+drugApplyId);
	     //获取vo的门诊
		 List<OutpatientStorage> outpatientstorage = outvo.getOutpatientstorage();
		 for (OutpatientStorage out : outpatientstorage) {
			     //新增判断--同一批次存在此药品直接修改数量
			     JSONArray if_addDrugsInStorage = drugmapper.if_addDrugsInStorage(out.getDrug().getDrugNumber(), out.getOutpatientPici());
			     if(if_addDrugsInStorage.size()>0) {
			    	 System.out.println("out.getOutpatientStorageAmount()-----------"+out.getOutpatientStorageAmount());
			    	 drugmapper.updateOutpatient_storage_amount(out.getOutpatientStorageAmount(), out.getDrug().getDrugNumber());
			     }else{
				  Drug drug = drugsdao.findById(out.getDrug().getDrugNumber()).get();
				 /* System.out.println("drug.getDrugNumber()-----------"+drug.getDrugNumber());
		    	  System.out.println("out.getOutpatientPici()-----------"+out.getOutpatientPici());
		    	  System.out.println("out.getOutpatientStorageAmount()-----------"+out.getOutpatientStorageAmount());
		    	  System.out.println("out.getOutpatientStorageStartdate()-----------"+out.getOutpatientStorageStartdate());
		    	  System.out.println("out.getOutpatientStorageStartdate()-----------"+out.getOutpatientStorageUsedate());*/
		    	  //新增药品
				 out.setDrug(drug);
				 //新增门诊库存
			     outpatientDao.save(out);
			  }
		 }
		/* 修改请领表的状态---根据请领主键  修改药房请领状态3(药房请领1---待发货 2待收货 3已收货)
		 * 入库类型 1为门诊  2为住院*/
		 drugmapper.updateDrugApply_state(3,1,drugApplyId);
		 //修改出库表状态1---0待收货   1已收货
		 drugmapper.updateOutBound_state(1, outbound_number);
	}
   
   //住院入库
   public void saveInHospitalStorage(InHospitalStorageVo inhosvo,Integer drugApplyId,Integer outbound_number) {
		 //获取vo的住院
	      List< InhospitalStorage> inHospitalStorage = inhosvo.getInHospitalStorage();
	      for (InhospitalStorage in : inHospitalStorage) {
	    	      //新增判断--同一批次存在此药品直接修改数量
			     JSONArray if_addDrugsInStorage = drugmapper.if_Inhospital_addDrugsInStorage(in.getDrug().getDrugNumber(), in.getInhospitalPici());
			     if(if_addDrugsInStorage.size()>0) {
			    	 System.out.println("in.getInhospitalStorageAmount()-----------"+in.getInhospitalStorageAmount());
			    	 drugmapper.updateInhospital_storage_amount(in.getInhospitalStorageAmount(), in.getDrug().getDrugNumber());
			     }else {
			    	System.out.println("住院新增-----------");
		    	    Drug drug = drugsdao.findById(in.getDrug().getDrugNumber()).get();
				  //新增药品
		    	  in.setDrug(drug);
		    	  //新增住院库存
		    	  inhosdao.save(in);
			     }
		}
		 //修改请领表的状态---根据请领主键  修改药房请领状态2
		 drugmapper.updateDrugApply_state(3,2,drugApplyId);
		 //修改出库表状态1
		 drugmapper.updateOutBound_state(1,outbound_number);
	}
   
   //门诊库存查询
   public JSONArray  select_OutPatientStorage_record(String drug_name,Integer days,Integer drug_number,Integer drug_pici) {
	   return drugmapper.select_OutPatientStorage_record(drug_name,days,drug_number,drug_pici);
   }
   
   //住院库存查询
   public JSONArray select_InhospitalStorage_record(String drug_name,Integer days,Integer drug_number,Integer drug_pici){
	   return drugmapper.select_InhospitalStorage_record(drug_name, days, drug_number, drug_pici);
   }
	
  // 门诊发药查询人员
   public JSONArray select_OutPatientStorage_people(String clinic_name) {
	   return drugmapper.select_OutPatientStorage_people(clinic_name);
   }
	
  //门诊发药根据人员查询详情
   public JSONArray select_OutPatientStorage_peopledetails(String cliniccard_id) {
	   return drugmapper.select_OutPatientStorage_peopledetails(cliniccard_id);
   }
   
     //门诊发药
 	public void AddOutPatient_Publicdrug(DrugfyVo drugfyVo) {
			//获取药品信息进行新增
			PublicDurg publicdurg = drugfyVo.getPublicdurg();
			
			//发药主表新增
			 PublicDurg saves= fydao.save(publicdurg);
			
			//发药详情
			List<PublicdurgDetail> details = drugfyVo.getPublicdurgdetail();
			
			Integer publicdurgShijishuliang=0; 
			BigDecimal publicdurgAllmoney=new BigDecimal(0);
			//循环
			for (PublicdurgDetail pur : details) {
			//添加医嘱信息
			DoctoradviceDetail yizhu = yzdao.findById(pur.getDoctoradviceDetail().getDocdetailsId()).get();
			pur.setDoctoradviceDetail(yizhu);
			
			//根据页面传过来的vo类-----得到药品单个发药数量
			Integer  drugeveryNumber = pur.getPdDetailsSjcount();
			//根据医嘱详情找到药品id
			Integer drugNumber =pur.getDoctoradviceDetail().getDrug().getDrugNumber();
			 System.out.println("根据医嘱详情找到药品id:"+drugNumber);
			//根据药品id找到所有药品批次
			JSONArray selectPici= drugmapper.selectPiciBydrugNumber(drugNumber,null);
			System.out.println("所有药品的批次:"+selectPici);
		    //根据药品id与药品批次找到药品库存数量
		    for (int i = 0; i <= selectPici.size(); i++) {
		    	PublicdurgDetail pd=new PublicdurgDetail();
		    	
		    	//添加发药详情---发药主表id
				pd.setPublicDurg(publicdurg);
				
				//重新赋值药品对象---医嘱详情id
				pd.setDoctoradviceDetail(yizhu);
				
		    	System.out.println("selectPici.size():"+selectPici.size());
		    	 //每个药品的批次
		    	Integer pici = selectPici.getJSONObject(i).getInteger("outpatient_pici");
		    	System.out.println("每个药品的批次:"+pici);
		    	//得到每个药品对应批次的库存数量
		    	JSONArray drugAmount= drugmapper.selectPiciBydrugNumber(drugNumber,pici);
		    	System.out.println("得到每个药品对应批次的库存数量drugAmount:"+drugAmount);
		    	Integer everyAmount = drugAmount.getJSONObject(0).getInteger("outpatient_storage_amount");
		    	System.out.println("每个药品对应批次everyAmount:"+everyAmount);
		    	//库存数量为零
		        if(everyAmount==0){
		        	System.out.println("everyAmount==0");
		        	continue;
		        }
		        
		    	//批次查出来此药品库存数量>=药品数量
		        if(drugeveryNumber<=everyAmount){
		        	System.out.println("批次查出来此药品库存数量>=药品数量");
		            //修改药房门诊库存数量
		        	drugmapper.updateOutpatient_Drugamount(drugeveryNumber, drugNumber, pici);
		        	//发药详情药品批次
		        	pd.setPdDetailsPici(pici);
		        	//发药每个实际数量
		        	pd.setPdDetailsSjcount(drugeveryNumber);
		        	//修改医嘱详情药品状态---2已发药
		        	advicedetailsmapper.updateAdviceDetailsSatus(2, yizhu.getDocdetailsId());
		        	
		        	//计算发药实际数量
		        	 publicdurgShijishuliang+=drugeveryNumber;
		        	 //修改发药实际数量
		        	 saves.setPublicdurgShijishuliang(publicdurgShijishuliang);
		        	 //药品金额
		        	 BigDecimal drugRetailPrice= pur.getDoctoradviceDetail().getDrug().getDrugRetailPrice();
		        	//修改总金额=每个批次药品价格x数量
		        	 publicdurgAllmoney = publicdurgAllmoney.add(drugRetailPrice.multiply(new BigDecimal(drugeveryNumber)));
		        	 saves.setPublicdurgAllmoney(publicdurgAllmoney);
		        	
		        	//发药详情新增
					fyxxdao.save(pd);
		        	break;
		        }
		        
		        //批次查出来此药品库存数量<=药品数量
		         if(drugeveryNumber>everyAmount){
		        	 System.out.println("库存数量批次不足！！！");
		        	 // 药品单个数量=3药品单个数量-库存数量 
		        	 drugeveryNumber=drugeveryNumber-everyAmount;
		        	 drugmapper.updateOutpatient_Drugamount(everyAmount, drugNumber,pici);
	        	     //发药详情药品批次
		        	 pd.setPdDetailsPici(pici);
		        	 //发药每个实际数量
		        	 pd.setPdDetailsSjcount(drugeveryNumber);
		        	 if(drugeveryNumber==0) {
		        		 advicedetailsmapper.updateAdviceDetailsSatus(2, yizhu.getDocdetailsId());
		        	 }
		        	 
		        	 //计算发药实际数量
		        	 publicdurgShijishuliang+=drugeveryNumber;
		        	 //修改发药实际数量
		        	 saves.setPublicdurgShijishuliang(publicdurgShijishuliang);
		        	 //药品金额
		        	 BigDecimal drugRetailPrice = pur.getDoctoradviceDetail().getDrug().getDrugRetailPrice();
		        	//修改总金额=每个批次药品价格x数量
		        	 publicdurgAllmoney = publicdurgAllmoney.add(drugRetailPrice.multiply(new BigDecimal(drugeveryNumber)));
		        	 saves.setPublicdurgAllmoney(publicdurgAllmoney);
		        	 
		        	  //发药详情新增
					  fyxxdao.save(pd);
		        	  continue;
		        }
		         
		          
			}
		}
	 }
 	
 	//门诊发药记录人
    public JSONArray  select_publicDrugPeople (@Param("clinic_name")String clinic_name) {
    	return drugmapper.select_publicDrugPeople(clinic_name);
    }

    //门诊发药记录
    public JSONArray select_publicDrug(@Param("publicdurg_id")Integer publicdurg_id) {
    	return drugmapper.select_publicDrug(publicdurg_id);
    }
    
    //住院发药记录
    public JSONArray  select_publicDrug_Inhospital(Integer publicdurg_type,Integer docdetails_type,Integer  publicdurg_id) {
    	return drugmapper.select_publicDrug_Inhospital(publicdurg_type,docdetails_type,publicdurg_id);
    }
    
    //住院发药记录 查看详情
    public JSONArray select_publicDrug_InhospitalDetails(Integer publicdurg_type,Integer  publicdurg_id,Integer docdetails_type) {
    	return drugmapper.select_publicDrug_InhospitalDetails(publicdurg_type, publicdurg_id,docdetails_type);
    }
    
    //住院发药
    public void outDrugInhospital(DrugfyVo dvo) {
    	        //发药主表
    			PublicDurg publicdurg = dvo.getPublicdurg();
    			//发药主表新增
    			PublicDurg public_drugsave = fydao.save(publicdurg);
    			
    			//发药实际数量--声明变量
    			Integer publicdurgShijishuliang=0;
    			
    			BigDecimal publicdurgAllmoney = new BigDecimal(0);
    			
    			List<PublicdurgDetail> publicdurgDetail = dvo.getPublicdurgdetail();
    			for (PublicdurgDetail pd : publicdurgDetail) {
    				pd.setPublicDurg(publicdurg);
    				
    				DoctoradviceDetail detail = yzdao.findById(pd.getDoctoradviceDetail().getDocdetailsId()).get();
    				System.out.println("医嘱详情主键："+pd.getDoctoradviceDetail().getDocdetailsId());
    				//重新赋值药品对象---医嘱详情id
    				pd.setDoctoradviceDetail(detail);
    				
    				//根据页面传过来的vo类-----得到药品单个发药数量
    				Integer  drugeveryNumber = pd.getPdDetailsSjcount();
    				//根据医嘱详情找到药品id
    				Integer drug_id = pd.getDoctoradviceDetail().getDrug().getDrugNumber();
    				System.out.println("根据医嘱详情找到药品id:"+drug_id);
    				//根据药品id找到所有药品批次
           		    JSONArray pici = drugmapper.selectInHosPiciBydrugNumber(drug_id,null);
    				System.out.println("所有药品的批次:"+pici);
    			    //根据药品id与药品批次找到药品库存数量
    			    for (int i = 0; i <= pici.size(); i++) {
    			    	PublicdurgDetail publicd=new PublicdurgDetail();
    			    	
    			    	//添加发药详情---发药主表id
    			    	publicd.setPublicDurg(publicdurg);
    					
    					//重新赋值药品对象---医嘱详情id
    			    	publicd.setDoctoradviceDetail(detail);
    			    	
    			    	System.out.println("selectPici.size():"+pici.size());
    			    	 //每个药品的批次
    			    	Integer inhospital_pici = pici.getJSONObject(i).getInteger("inhospital__pici");
    			    	System.out.println("每个药品的批次:"+inhospital_pici);
    			    	//得到每个药品对应批次的库存数量
             		    JSONArray InHosdrugAmount = drugmapper.selectInHosPiciBydrugNumber(drug_id, inhospital_pici);
    			    	System.out.println("得到每个药品对应批次的库存数量InHosdrugAmount:"+InHosdrugAmount);
    			    	Integer InhoseveryAmount = InHosdrugAmount.getJSONObject(0).getInteger("inhospital__storage_amount");
    			    	System.out.println("每个药品对应批次InhoseveryAmount:"+InhoseveryAmount);
    			    	//库存数量为零
    			        if(InhoseveryAmount==0){
    			        	System.out.println("InhoseveryAmount==0");
    			        	continue;
    			        }
    			        
    			    	//批次查出来此药品库存数量>=药品数量
    			        if(drugeveryNumber<=InhoseveryAmount){
    			        	System.out.println("批次查出来此药品库存数量>=药品数量");
    			        	//修改库存数量
    			        	drugmapper.updateInHospital_Drugamount(drugeveryNumber, drug_id, inhospital_pici);
    			        	publicd.setPdDetailsPici(inhospital_pici);
    			        	//发药每个实际数量
    			        	publicd.setPdDetailsSjcount(drugeveryNumber);
    			        	//修改医嘱详情药品状态---2已发药
    			        	advicedetailsmapper.updateAdviceDetailsSatus(2, detail.getDocdetailsId());
    			        	//修改药房库存
    			        	drugmapper.updateInhospital_samllstorage_amount(drugeveryNumber,drug_id, inhospital_pici);
    			        	 //计算发药实际总数量
    			        	publicdurgShijishuliang+=drugeveryNumber;
    			        	 //修改发药实际总数量
    			        	public_drugsave.setPublicdurgShijishuliang(publicdurgShijishuliang);
    			        	 //药品金额
    			        	BigDecimal drugRetailPrice = detail.getDrug().getDrugRetailPrice();
    			        	//修改总金额=每个批次药品价格x数量
    			        	publicdurgAllmoney=publicdurgAllmoney.add(drugRetailPrice.multiply(new BigDecimal(drugeveryNumber)));
    			        	public_drugsave.setPublicdurgAllmoney(publicdurgAllmoney);
    			        	//发药详情新增
    	    				fyxxdao.save(publicd);
    			        	break;
    			        }
    			        
    			        //批次查出来此药品库存数量<=药品数量
    			         if(drugeveryNumber>InhoseveryAmount){
    			        	 System.out.println("drugeveryNumber>everyAmount");
    			        	 // 药品单个数量=3药品单个数量-库存数量 
    			        	 drugeveryNumber=drugeveryNumber-InhoseveryAmount;
    			        	 drugmapper.updateInHospital_Drugamount(InhoseveryAmount, drug_id, inhospital_pici);
    			        	 //修改批次
    			        	 publicd.setPdDetailsPici(inhospital_pici);
    			        	 //发药每个实际数量
     			        	 publicd.setPdDetailsSjcount(drugeveryNumber);
    			        	  //修改药房小库存
     			        	 drugmapper.updateInhospital_samllstorage_amount(drugeveryNumber,drug_id, inhospital_pici);
    			        	 
     			        	 //计算发药实际数量
     			        	 publicdurgShijishuliang+=drugeveryNumber;
     			        	 //修改发药实际数量
     			        	 public_drugsave.setPublicdurgShijishuliang(publicdurgShijishuliang);
     			        	 //药品金额
     			        	 BigDecimal drugRetailPrice = detail.getDrug().getDrugRetailPrice();
     			        	//修改总金额=每个批次药品价格x数量
     			        	 publicdurgAllmoney = drugRetailPrice.multiply(new BigDecimal(drugeveryNumber));
     			        	 public_drugsave.setPublicdurgAllmoney(publicdurgAllmoney);
     			        	 //发药详情新增
     	    				 fyxxdao.save(publicd);
     			        	 if(drugeveryNumber==0) {
    			        		 advicedetailsmapper.updateAdviceDetailsSatus(2, detail.getDocdetailsId());
    			        	 }
    			        	 continue;
    			        }
    				}
    				
    			}
    }
    
  // 门诊看诊药品查询
  public JSONArray select_OutPatientDrug_record(String drug_name) {
	   return drugmapper.select_OutPatientDrug_record(drug_name);
  }
  
    //门诊药房退药新增---退给药库
	public void saveReturn(ReturndrugVo ReturndrugVo) {
		//获取退药订单进行新增
		ReturnGood good = ReturndrugVo.getGood();
		
		//时间
		good.setReturnGoodsTime(new  Timestamp(new java.util.Date().getTime()));
		ReturnGood save = gooddao.save(good);
		
		List<ReturnGoodsDetail> goods = ReturndrugVo.getGooddetail();
		//循环
		for (ReturnGoodsDetail pur : goods) {
			//添加订单信息
			pur.setReturnGood(good);
			//查询药品
			JSONArray select_InventroyNumber = drugmapper.select_InventroyNumber(pur.getInventory().getInventoryNumber());
			Integer inventory_number=select_InventroyNumber.getJSONObject(0).getInteger("inventory_number"); 
			Inventory inventory=new Inventory();
			inventory.setInventoryNumber(inventory_number);
			//重新赋值一下药品对象
			pur.setInventory(inventory);
			
			//减去门诊库存
			drugmapper.updateOutpatient_Drugamount(pur.getReturnDetailsQuantity(),
			pur.getInventory().getDrug().getDrugNumber(), pur.getReturnDetailsPici());
			
			gooddeyaildao.save(pur);
		}
			
	}
	
	//根据药品编号与批次查询库存主键id
	public JSONArray select_inventoryDrug_number(@Param("drug_number")Integer drug_number,@Param("inventory_details_batch")Integer inventory_details_batch) {
		return drugmapper.select_inventoryDrug_number(drug_number, inventory_details_batch);
	}

	  //住院药房退药新增---退给药库
		public void saveInhosptialReturn(ReturndrugVo ReturndrugVo) {
			//获取退药订单进行新增
			ReturnGood good = ReturndrugVo.getGood();
			
			//时间
			good.setReturnGoodsTime(new  Timestamp(new java.util.Date().getTime()));
			ReturnGood save = gooddao.save(good);
			
			List<ReturnGoodsDetail> goods = ReturndrugVo.getGooddetail();
			//循环
			for (ReturnGoodsDetail pur : goods) {
				//添加订单信息
				pur.setReturnGood(good);
				//查询药品
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				//重新赋值一下药品对象
				pur.setInventory(inventory);
				
				//减去住院库存
				drugmapper.updateInHospital_Drugamount(pur.getReturnDetailsQuantity(),
				pur.getInventory().getDrug().getDrugNumber(), pur.getReturnDetailsPici());
				
				gooddeyaildao.save(pur);
			}
				
		}
		
		//查询退药信息
		public JSONArray  select_returnDrug_record(Integer return_goods_id) {
			return drugmapper.select_returnDrug_record(return_goods_id);
		}
		
		//查询退药详情信息
		public JSONArray  select_returnDrug_recordDetails(Integer return_goods_id) {
			return drugmapper.select_returnDrug_recordDetails(return_goods_id);
		}
		
		// 门诊药品出库数量
		 public JSONArray select_outpatient_outAmount(Integer drug_id,Integer publicdurg_type,Integer pd_details_pici) {
			 return drugmapper.select_outpatient_outAmount(drug_id, publicdurg_type,pd_details_pici);
		 }
		 
		 // 门诊盘点药品统计入库数量
		 public JSONArray select_outpatient_InAmount(Integer drug_id,Integer drugapply_type,Integer out_details_pici) {
			 return drugmapper.select_outpatient_InAmount(drug_id,drugapply_type,out_details_pici);
		 }
		 
		//盘点门诊库存查询
		 public JSONArray select_CheckOutPatientStorage_record(Integer drug_number,Integer drug_pici) {
			 return drugmapper.select_CheckOutPatientStorage_record(drug_number,drug_pici);
		 }
		 
		//盘点住院库存查询 
		 public JSONArray select_CheckInhospitalStorage_record(Integer drug_number,Integer drug_pici) {
			 return drugmapper.select_CheckInhospitalStorage_record(drug_number,drug_pici);
		 }
		 
		// 门诊1住院2查询亏损入库库记录
	   public JSONArray  select_oupatient_bad_in_amount(Integer drugapply_type,Integer drugnumber,Integer out_details_pici) {
		   return drugmapper.select_oupatient_bad_in_amount(drugapply_type,drugnumber,out_details_pici);
	   }
		 
		//门诊查询亏损出库记录
		public JSONArray  select_oupatient_badamount(Integer publicdurg_type, Integer drug_number,Integer pd_details_pici) {
			return drugmapper.select_oupatient_badamount(publicdurg_type, drug_number,pd_details_pici);
		}
		
		//药品销毁
		public void saveDestructions(DestructionVo DestructionVo,String return_id) {
			//获取销毁订单进行新增
			Destroy destroy = DestructionVo.getDestroy();
			
			Destroy save = destroydao.save(destroy);
			
			List<DestryDetail> destroys = DestructionVo.getDestrydetail();
			//循环
			for (DestryDetail pur : destroys) {
				//添加订单信息
				pur.setDestroy(destroy);
				//查询药品
				Inventory inventory = Inventorydao.findById(pur.getInventory().getInventoryNumber()).get();
				//重新赋值一下药品对象
				pur.setInventory(inventory);
				
				//修改退药状态---5已退药
				drugmapper.update_return_state(Integer.valueOf(return_id));
				
				destrydetaildao.save(pur);
			}
				
		}
		
		//统计退药数量 
		public JSONArray return_good_amountBydrug_number_pici(String return_goods_type,Integer drug_number,Integer return_details_pici) {
			return drugmapper.return_good_amountBydrug_number_pici(return_goods_type, drug_number, return_details_pici);
		}
		

		//销毁数量 
		public JSONArray destroy_good_amountBydrug_number_pici(Integer destroy_state,Integer drug_number,Integer destroy_pici){
			return drugmapper.destroy_good_amountBydrug_number_pici(destroy_state, drug_number, destroy_pici);
		}
		
		//盘点入库
		public void add_checks(DrugscheckVo chekvo) {
			DrugstorageCheck drugcheck=chekvo.getDrugc();
			chekvo.getDrugc().setDrugchekTime(new Timestamp(new java.util.Date().getTime()));
			
			//亏损总数量
			BigDecimal bad_total=new BigDecimal(0);
			//亏损总金额
			Integer bad_totalmoney=0;
			List<DrugstoragecheckDetail> drugcdetail= chekvo.getDrugcdetail();
			for (DrugstoragecheckDetail cDetail : drugcdetail) {
				//总数量差
				bad_total=bad_total.add(new BigDecimal(cDetail.getDrugchekdetailsShuliangcha()));
				//System.out.println("亏损总数量："+bad_total);
				
				//亏损金额
				int drugRetailPrice =(cDetail.getDrugchekdetailsShijinumber()*cDetail.getDrugchekdetailsSort())-(cDetail.getDrugtuiyao()*cDetail.getDrugchekdetailsSort());
				bad_totalmoney+=drugRetailPrice;
				
			}
			
			drugcheck.setDrugcheckDifferencemoney(new BigDecimal(bad_totalmoney));
			drugcheck.setDrugcheckTwopeople(String.valueOf(bad_total));
			//盘点主表
			Drugcdao.save(drugcheck);
			
			for(DrugstoragecheckDetail checkDetail : drugcdetail) {
				checkDetail.setDrugstorageCheck(drugcheck);
				//根据药品id查询库存id
				JSONArray select_InventroyNumber = drugmapper.select_InventroyNumber(checkDetail.getInventory().getInventoryNumber());
				Integer inventory_number=select_InventroyNumber.getJSONObject(0).getInteger("inventory_number"); 
				Inventory inventroys=new Inventory();
				inventroys.setInventoryNumber(inventory_number);
				//System.out.println("inventory_number-----:"+inventory_number);
				checkDetail.setInventory(inventroys);
				
				Integer Drug_Number = checkDetail.getInventory().getInventoryNumber();
				Integer Drug_pici =checkDetail.getDrugchekdetailsPici();
				Integer Drug_amount=checkDetail.getDrugchekdetailsShijinumber();
				//System.out.println("Drug_pici-----:"+Drug_pici+"---Drug_Number:"+Drug_Number+"---:"+checkDetail.getDrugchekdetailsShuliangcha());

				/*System.out.println("Drug_Number:"+Drug_Number);
				System.out.println("Drug_pici:"+Drug_pici);
				System.out.println("checkDetail.getDrugchekdetailsShijinumber()---:"+checkDetail.getDrugchekdetailsShijinumber());*/
				
				//修改门诊库存数量
				drugmapper.updateOutpatient_DrugamountBycheck(Drug_amount,Drug_Number,Drug_pici);
				
				//单个亏损金额
				int badEveryMOney=(checkDetail.getDrugchekdetailsShijinumber()*checkDetail.getDrugchekdetailsSort())-(checkDetail.getDrugtuiyao()*checkDetail.getDrugchekdetailsSort());
				checkDetail.setDrugchekdetailsBook(badEveryMOney);
				/*System.out.println("2单个库存数量："+checkDetail.getDrugchekdetailsShijinumber());
				System.out.println("单个数量差："+checkDetail.getDrugchekdetailsShuliangcha());
				System.out.println("单个亏损金额："+badEveryMOney);	*/

				//盘点详情表
				drugcdetaildao.save(checkDetail);
			}
		
		}
		
		//查看盘点
		public JSONArray select_check() {
			return drugmapper.select_check();
		}
		   
		//盘点查看详情
		public JSONArray select_checkDetails(Integer drugchek_id) {
			return drugmapper.select_checkDetails(drugchek_id);
		}
}
